package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    // 用户下单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        //去 address_book表中查询
        AddressBook addressBookById = addressBookService.getById(orders.getAddressBookId());
        Long userId = addressBookById.getUserId();
        String phone = addressBookById.getPhone();
        String address = (addressBookById.getProvinceName() == null ? "" : addressBookById.getProvinceName())
                + (addressBookById.getCityName() == null ? "" : addressBookById.getCityName())
                + (addressBookById.getDistrictName() == null ? "" : addressBookById.getDistrictName())
                + (addressBookById.getDetail() == null ? "" : addressBookById.getDetail());
        String consignee = addressBookById.getConsignee();
        //查询用户数据
        User user = userService.getById(userId);
        //根据用户Id 去 购物车中 查询
        LambdaQueryWrapper<ShoppingCart> shoppingCartLQW = new LambdaQueryWrapper<>();
        shoppingCartLQW.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLQW);
        //准备保存 订单orders 此处 orderId 不是插入表时雪花算法自动生成
        //而是由工具类 IdWorker.getId() 生成
        long orderId = IdWorker.getId();
        orders.setId(orderId);
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPhone(phone);
        orders.setAddress(address);
        orders.setUserName(user.getName());
        orders.setConsignee(consignee);
        BigDecimal totalAmount = new BigDecimal(0);//总价
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            BigDecimal amount = shoppingCart.getAmount();
            totalAmount = totalAmount.add(number.multiply(amount));
            //保存订单明细数据 点了哪些菜品或套餐  需要 订单Id
            //shoppingCart --> orderDetail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail, "userId", "createTime");
            orderDetail.setOrderId(orderId);
            orderDetail.setId(IdWorker.getId());
            orderDetailList.add(orderDetail);
        }
        //在没有id的情况下, mp自带雪花生成算法 saveBatch(xxxList) 生成id的时候 可能会出错
        orderDetailService.saveBatch(orderDetailList);
        orders.setAmount(totalAmount);
        orderService.save(orders);
        //删除当前用户的购物车数据
        shoppingCartLQW.clear();
        shoppingCartLQW.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(shoppingCartLQW);
        return R.success("下单成功");
    }

    // 用户查看订单详情
    @GetMapping("/userPage")
    public R<Map<String, Object>> list(Integer page, Integer pageSize) {
        IPage<Orders> orderPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> orderLQW = new LambdaQueryWrapper<>();
        orderService.page(orderPage, orderLQW);
        List<Orders> orderList = orderPage.getRecords();
//        List<OrdersDto> ordersDtos = new ArrayList<>();
//        for (Orders order : orderList) {
//            OrdersDto ordersDto = new OrdersDto();
//            BeanUtils.copyProperties(order, ordersDto);
//            Long orderId = order.getId();
//            LambdaQueryWrapper<OrderDetail> orderDetailLQW = new LambdaQueryWrapper<>();
//            orderDetailLQW.eq(OrderDetail::getOrderId, orderId);
//            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLQW);
//            ordersDto.setOrderDetails(orderDetails);
//            ordersDtos.add(ordersDto);
//        }
        Map<String, Object> map = new HashMap<>();
        map.put("records", orderList);
        map.put("total", orderList.size());
        return R.success(map);
    }

    // 商家查看订单详情
    @GetMapping("/page")
    public R<Map<String, Object>> list2(Integer page, Integer pageSize) {
        return this.list(page, pageSize);
//        IPage<Orders> orderPage = new Page<>(page, pageSize);
//        LambdaQueryWrapper<Orders> orderLQW = new LambdaQueryWrapper<>();
//        orderService.page(orderPage, orderLQW);
//        List<Orders> orderList = orderPage.getRecords();
//        List<OrdersDto> ordersDtos = new ArrayList<>();
//        for (Orders order : orderList) {
//            OrdersDto ordersDto = new OrdersDto();
//            BeanUtils.copyProperties(order, ordersDto);
//            Long orderId = order.getId();
//            LambdaQueryWrapper<OrderDetail> orderDetailLQW = new LambdaQueryWrapper<>();
//            orderDetailLQW.eq(OrderDetail::getOrderId, orderId);
//            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLQW);
//            ordersDto.setOrderDetails(orderDetails);
//            ordersDtos.add(ordersDto);
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("records", ordersDtos);
//        map.put("total", orderList.size());
//        return R.success(map);
    }

    // 商家修改订单状态
    @PutMapping
    public R<String> changeStatus(@RequestBody Orders orders) {
        log.info("orders : {}", orders);
        orderService.updateById(orders);
        return R.success("订单状态修改成功");
    }

}